import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class SessionManager {
    private static List<Session> sessions = new ArrayList<>();
    private static List<CinemaHall> halls = new ArrayList<>();
    private static List<Ticket> tickets = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);
    private static int sessionIdCounter = 1;
    private static MovieManager movieManager = new MovieManager();

    static {
        halls.add(new CinemaHall("黄金厅", 8, 10));
        halls.add(new CinemaHall("白银厅", 10, 12));
        halls.add(new CinemaHall("翡翠厅", 7, 8));
        halls.add(new CinemaHall("钻石厅", 7, 8));
        halls.add(new CinemaHall("宝石厅", 8, 9));
    }

    public void addSession(User manager) {
        System.out.print("请输入影片名: ");
        String movieName = scanner.nextLine();
        if (movieManager.findMovieByName(movieName) == null) {
            System.out.println("影片不存在");
            return;
        }

        System.out.print("请输入放映厅(黄金厅/白银厅/翡翠厅/钻石厅/宝石厅): ");
        String hall = scanner.nextLine();
        System.out.print("请输入放映时间(yyyy-MM-dd HH:mm): ");
        String timeStr = scanner.nextLine();
        System.out.print("请输入票价: ");
        double price = scanner.nextDouble();
        scanner.nextLine();

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date time = sdf.parse(timeStr);
            sessions.add(new Session(sessionIdCounter++, movieName, hall, time, price));
            System.out.println("场次添加成功");
            logOperation(manager.getUsername(), "添加场次" + movieName + "(" + hall + ")", new Date());
        } catch (ParseException e) {
            System.out.println("时间格式错误");
        }
    }

    public void modifySession(User manager) {
        System.out.print("请输入要修改的场次ID: ");
        int sessionId = getValidIntegerInput();
        Session session = findSessionById(sessionId);
        if (session == null) {
            System.out.println("场次不存在");
            return;
        }

        System.out.println("1. 修改放映时间");
        System.out.println("2. 修改票价");
        System.out.print("选择操作: ");
        int choice = getValidIntegerInput();

        if (choice == 1) {
            System.out.print("请输入新的放映时间(yyyy-MM-dd HH:mm): ");
            String newTimeStr = scanner.nextLine();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date newTime = sdf.parse(newTimeStr);
                session.setTime(newTime);
                System.out.println("放映时间修改成功");
                logOperation(manager.getUsername(), "修改场次" + sessionId + "放映时间", new Date());
            } catch (ParseException e) {
                System.out.println("时间格式错误");
            }
        } else if (choice == 2) {
            System.out.print("请输入新的票价: ");
            double newPrice = scanner.nextDouble();
            scanner.nextLine();
            session.setPrice(newPrice);
            System.out.println("票价修改成功");
            logOperation(manager.getUsername(), "修改场次" + sessionId + "票价", new Date());
        }
    }

    public void deleteSession(User manager) {
        System.out.print("请输入要删除的场次ID: ");
        int sessionId = getValidIntegerInput();
        Session session = findSessionById(sessionId);
        if (session == null) {
            System.out.println("场次不存在");
            return;
        }

        if (hasTicketForSession(sessionId)) {
            System.out.println("该场次已有售票，无法删除");
            return;
        }

        System.out.print("确定删除? (y/n): ");
        if (scanner.nextLine().equals("y")) {
            sessions.remove(session);
            System.out.println("场次删除成功");
            logOperation(manager.getUsername(), "删除场次" + sessionId, new Date());
        }
    }

    public void listSessions() {
        System.out.println("=== 场次列表 ===");
        for (Session session : sessions) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            System.out.println("场次ID: " + session.getSessionId() +
                    " 影片: " + session.getMovieName() +
                    " 放映厅: " + session.getHall() +
                    " 时间: " + sdf.format(session.getTime()) +
                    " 票价: " + session.getPrice());
        }
    }

    public void autoArrangeSessions(User manager) {
        List<Movie> sortedMovies = new ArrayList<>();
        System.out.println("自动排片功能开发中");
        logOperation(manager.getUsername(), "执行自动排片", new Date());
    }

    public void viewSalesData() {
        System.out.println("\n1. 查看当日销售数据");
        System.out.println("2. 查看当周销售数据");
        System.out.println("3. 查看当月销售数据");
        System.out.print("选择操作: ");
        int choice = getValidIntegerInput();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(today);

        switch (choice) {
            case 1:
                System.out.println("=== 当日销售数据 ===");
                calculateSales(sdf.format(today), sdf.format(today));
                break;
            case 2:
                cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                String weekStart = sdf.format(cal.getTime());
                cal.add(Calendar.DATE, 6);
                String weekEnd = sdf.format(cal.getTime());
                System.out.println("=== 当周销售数据（" + weekStart + "至" + weekEnd + "） ===");
                calculateSales(weekStart, weekEnd);
                break;
            case 3:
                cal.set(Calendar.DAY_OF_MONTH, 1);
                String monthStart = sdf.format(cal.getTime());
                cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
                String monthEnd = sdf.format(cal.getTime());
                System.out.println("=== 当月销售数据（" + monthStart + "至" + monthEnd + "） ===");
                calculateSales(monthStart, monthEnd);
                break;
        }
    }

    private void calculateSales(String startDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int totalTickets = 0;
        double totalRevenue = 0;

        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            for (Ticket ticket : tickets) {
                Date sessionDate = ticket.getSession().getTime();
                if (sessionDate.after(start) && sessionDate.before(end) ||
                        sessionDate.equals(start) || sessionDate.equals(end)) {
                    totalTickets++;
                    totalRevenue += ticket.getPrice();
                }
            }

            System.out.println("售票总数: " + totalTickets);
            System.out.println("总销售额: " + totalRevenue);
        } catch (ParseException e) {
            System.out.println("日期解析错误");
        }
    }

    public void showSessionSeats(int sessionId) {
        Session session = findSessionById(sessionId);
        if (session == null) {
            System.out.println("场次不存在");
            return;
        }

        CinemaHall hall = null;
        for (CinemaHall h : halls) {
            if (h.getName().equals(session.getHall())) {
                hall = h;
                break;
            }
        }

        if (hall == null) {
            System.out.println("放映厅信息错误");
            return;
        }

        System.out.println("=== " + session.getHall() + " 座位图 ===");
        System.out.println("屏幕在此处");
        System.out.println("-------------------");

        for (int row = 1; row <= hall.getRows(); row++) {
            StringBuilder rowStr = new StringBuilder();
            for (int seat = 1; seat <= hall.getSeatsPerRow(); seat++) {
                String seatNum = row + "-" + seat;
                if (isSeatSold(sessionId, seatNum)) {
                    rowStr.append("X ");
                } else {
                    rowStr.append("O ");
                }
            }
            System.out.println(rowStr.toString());
        }

        System.out.println("-------------------");
        System.out.println("O: 空座, X: 已售");
    }

    public Session findSessionById(int sessionId) {
        for (Session session : sessions) {
            if (session.getSessionId() == sessionId) {
                return session;
            }
        }
        return null;
    }

    public boolean isSeatSold(int sessionId, String seat) {
        for (Ticket ticket : tickets) {
            if (ticket.getSession().getSessionId() == sessionId &&
                    ticket.getSeat().equals(seat)) {
                return true;
            }
        }
        return false;
    }

    private boolean hasTicketForSession(int sessionId) {
        for (Ticket ticket : tickets) {
            if (ticket.getSession().getSessionId() == sessionId) {
                return true;
            }
        }
        return false;
    }

    public void addTicket(Ticket ticket) {
        tickets.add(ticket);
    }

    public void removeTicket(String ticketId) {
        tickets.removeIf(ticket -> ticket.getTicketId().equals(ticketId));
    }

    private int getValidIntegerInput() {
        while (true) {
            try {
                return Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的整数");
            }
        }
    }

    private void logOperation(String operator, String action, Date time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String log = sdf.format(time) + " - 操作人: " + operator + " - 操作: " + action;
        System.out.println("[日志] " + log);
    }
}
